package com.suzhe.ymall.cart.service.impl;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.suzhe.ymall.cart.pojo.CartSku;
import com.suzhe.ymall.cart.service.ICartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CartServiceImpl implements ICartService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void saveOrUpdate(CartSku cartSku) {
        CartSku oldCart = findBySkuId(cartSku.getSkuId());
        if (oldCart != null){
            updateNum(cartSku);
        }else{
            mongoTemplate.save(cartSku);
        }

    }

    @Override
    public List<CartSku> findByUserId(Integer userId) {
        Query query = new Query();
        return mongoTemplate.find(query, CartSku.class);

    }

    @Override
    public void delBySkuIds(List<Integer> skuIds) {
        Query query=new Query(Criteria.where("skuId").in(skuIds));
        DeleteResult result = mongoTemplate.remove(query, CartSku.class);

        log.debug("delCartBySkuIds result:",result);
    }

    @Override
    public CartSku findBySkuId(Integer skuId) {
        Query query = new Query(Criteria.where("skuId").is(skuId));
        CartSku cart = mongoTemplate.findOne(query, CartSku.class);
        return cart;
    }

    @Override
    public void updateNum(CartSku cartSku){
        Query query = new Query(Criteria.where("_id").is(cartSku.getId()));
        Update update = new Update()
                .set("num", cartSku.getNum())
                .set("updateTime", new Date());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, CartSku.class);
        log.debug("updateCartNum result:",updateResult);
    }


}
